<?php
/**
 * Oracle 接口类
 */

namespace App\Utils;

class Oracle
{
    private static $account;
    private static $password;
    private static $db_connect_string;
    private static $db_client_charset;
    private static $instance;

    public function __construct()
    {
        self::$account = config('app.pdm_account');
        self::$password = config('app.pdm_password');
        self::$db_connect_string = config('app.pdm_db_connect_string');
        self::$db_client_charset = config('app.pdm_db_client_charset');

        if ($_instance = oci_connect(self::$account, self::$password, self::$db_connect_string,
            self::$db_client_charset)) {
            self::$instance = $_instance;
        } else {
            $e = oci_error();
            echo $e['message'];
            die('连接失败');
        }
    }

    private function __clone()
    {
    }

    public static function instance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new Oracle();
        }

        return self::$instance;
    }

    /*项目信息：v_bks_project；
    任务通知单信息：v_bks_tasklist；
    零件净重信息：v_bks_pweight；*/
    /**
     * @desc 执行sql
     * @param  string  $sql
     * @return array
     */
    public function execute($sql = 'select * from  v_bks_project  where rownum < 101')
    {
        $query_parse = oci_parse(self::$instance, $sql); // 配置SQL语句，准备执行
        if (!$query_parse) {
            $e = oci_error(self::$instance);
            die($e['message']);
        }
        $query_result = oci_execute($query_parse, OCI_DEFAULT); // 执行SQL。OCI_DEFAULT表示不要自动commit
        if (!$query_result) {
            $e = oci_error($query_parse);
            die($e['message']);
        }

        $arr = [];
        $i = '-1';
        while (($row = oci_fetch_array($query_parse, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {//返回关联数据并创建null
            $i++;
            foreach ($row as $key => $item) {
                $arr[$i][$key] = iconv("gb2312", "utf-8//TRANSLIT", $item);
            }
        }
        $this->close();

        return $arr;    //二维关联数组
    }

    //关闭连接
    public function close()
    {
        oci_close(self::$_instance);
    }
}
